import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/common_api.dart';
import 'package:sainbainu/common/apis/feedback_api.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/models/response/upload_response.dart';
import 'package:sainbainu/common/repositories/common_repository.dart';
import 'package:sainbainu/common/repositories/feedback_repository.dart';
import 'package:sainbainu/common/services/ali_oss.dart';
import 'package:sainbainu/common/utils/compress.dart';
import 'package:sainbainu/common/utils/custom_exception.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/widgets/widget.dart';

import 'index.dart';

const double sidePadding = 15;
const double crossAxisSpacing = 10;
const double itemHeight = 80;

class FeedbackController extends GetxController {
  FeedbackController();

  final state = FeedbackState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    state.contentController = TextEditingController()
      ..addListener(() {
        state.feedbackRequest.feedbackContent = state.contentController.text;
      });
    state.feedbackRepository = FeedbackRepository(FeedbackApi());
    state.pagerRequest = PagerRequest();
    state.commonRepository = CommonRepository(CommonApi());
    state.imageUploaderController = ImageUploaderController();

    getList();

    /// 计算图片比例
    var gridWidth = MediaQuery.of(Get.context!).size.width - sidePadding * 2;
    var itemWidth = (gridWidth - crossAxisSpacing * 2) / 3;
    state.itemRatio = itemWidth / itemHeight;
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.refreshController.dispose();
    state.contentController.dispose();
  }

  /// 获取内容列表
  Future getList({bool refresh = true}) async {
    if (refresh) {
      state.pagerRequest.pageNum = 1;
    }
    var res = await state.feedbackRepository.list(
      state.pagerRequest,
    );
    if (refresh) {
      state.feedbackResponse.rows = res.rows;
    } else {
      state.feedbackResponse.rows.addAll(res.rows);
    }

    state.feedbackResponse.total = res.total;
    state.hasMore =
        state.pagerRequest.pageNum * state.pagerRequest.pageSize < res.total;
    state.pagerRequest.pageNum++;
    update(['list']);
  }

  /// 下拉刷新
  Future onRefresh() async {
    try {
      await getList();
      if (state.feedbackResponse.rows.isEmpty) {
        state.refreshController.finishRefresh(IndicatorResult.noMore);
      } else {
        state.refreshController.finishRefresh(IndicatorResult.success);
      }
      state.refreshController.resetFooter();
    } catch (e) {
      state.refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  /// 上拉下载
  Future onRichBottom() async {
    try {
      if (state.hasMore) {
        await getList(refresh: false);
      }
      if (!state.hasMore) {
        state.refreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.refreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 预览多张
  void handlePreviewList(String cover, List<String> images) {
    int index = images.indexOf(cover);
    Get.to(
      () => PhotoViewSaver(
        images: images,
        index: index,
      ),
      transition: Transition.fadeIn,
      fullscreenDialog: true,
    );
  }

  /// 上传
  Future<String> handleUpload(File file) async {
    UploadResponse res = await AliOssService.to.upFile(
      file.path,
      mediaType: UploadMediaType.image,
    );
    return res.url;
  }

  /// 上传封面
  Future<List<String>> handleUploadImages() async {
    // AssetEntity 转 file 对象
    List<File> fileList = await Util.assetEntityToFiles(state.feedbackImages);
    if (fileList.isEmpty) {
      throw CustomException('图片解析失败，请稍后再试');
    }
    // 压缩
    fileList = await CompressUtil().compressImages(
      CompressImagesOptions(fileList),
    );
    // 执行上传
    List<String> urls = [];
    int index = 1;
    for (var file in fileList) {
      LoadingUtil.showLoading(text: '正在上传第$index张');
      try {
        var url = await handleUpload(file);
        urls.add(url);
        index++;
      } catch (e) {
        continue;
      }
    }
    LoadingUtil.dismiss();
    return urls;
  }

  /// 确认反馈
  void handleSubmit() async {
    try {
      if (state.feedbackRequest.feedbackContent == null ||
          state.feedbackRequest.feedbackContent!.isEmpty) {
        throw CustomException('请输入反馈内容');
      }
      if (state.feedbackImages.isNotEmpty) {
        List<String> urls = await handleUploadImages();
        state.feedbackRequest.image = urls.join(',');
      }
      LoadingUtil.showLoading(text: '正在提交');
      await state.feedbackRepository.add(state.feedbackRequest);
      LoadingUtil.dismiss();
      await showOkAlertDialog(
        context: Get.context!,
        title: '反馈成功'.tr,
        message: '感谢您的反馈，我们会尽快查阅您的问题，并给出回复。'.tr,
        okLabel: '知道了'.tr,
        style: AdaptiveStyle.iOS,
      );
      Get.back();
      reset();
      onRefresh();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.message);
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }

  /// 重置
  reset() {
    state.contentController.text = '';
    state.imageUploaderController.clear();
    state.feedbackRequest.feedbackContent = '';
    state.feedbackRequest.image = '';
    state.feedbackImages.clear();
  }
}
